/**
 * WidgetEventPagingInput module
 */

import React,{Component} from "react";
import { connect } from 'dva';
import classnames from 'classnames';
import { bindActionCreators } from 'redux';
import widgetsActions from '../../../actions/Editor/widgets';
import editorActions from '../../../actions/Editor/editor';
class WidgetEventPagingInput extends Component{
    getInitialProps(){
        return {
            form: {},
            pages: []
        }
    }
    componentWillMount(){
        this.page_indexs = [];
        const {pages,selectedPageId} = this.props;
        pages.map(function (page){
            var id = page.page_id;
            var label = ""+$._("No.")+"" + page.title + ""+$._("Page")+"";
            if (id != selectedPageId){
                this.page_indexs.push({
                    id: id,
                    label: label
                });
            }
        }, this);
    }
    componentDidMount(){
        this.initElements();
    }
    initElements(){
        this.elements = {
            pageSelect: $(this.refs.pageSelect)
        };
    }
    handleOnChangePage(){
        const {widget,updateWidget,setState} = this.props;
        let page_index = this.elements.pageSelect.val();
        let data = widget;
        data.action = $.extend(true, {}, widget.action, {page_index: page_index});
        setState({selectedWidget: data});
        updateWidget(data);
    }
    render(){
        const {widget} = this.props;
        const {action} = widget || {};
        const {page_index} = action || '';
        return (
            <div className="form-group page_span">
                <span>{$._('Page to')}</span>
                <select ref="pageSelect" onChange={() => this.handleOnChangePage()} value={page_index} className='form-control'>
                    <option value="">{$._("Please choose")}</option>
                    {
                        this.page_indexs.map(function (page_index){
                            return (
                                <option key={page_index.id} value={page_index.id}>{page_index.label}</option>
                            )
                        })
                    }
                </select>
            </div>
        )
    } 
}

const mapStateToProps = ({ editor, widgets ,pages}) => {
  const pageId = editor.selectedPageId;
  return {
      status: editor.status,
      widget: editor.selectedWidget,
      widgets: widgets.filter(w => w.page_id === pageId),
      pages,
      selectedPageId: pageId,
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({...widgetsActions,...editorActions}, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(WidgetEventPagingInput);
